<template>
	<uni-card title="商品SKU">
		<template v-slot:title>
			<view class="gl-header">
				<view style="display: flex;align-items: center;">
					<uni-icons v-if="isback" type="undo-filled" size="40" color="#4cd964" @click="swiperBack"
						style="padding: 3px;border-radius: 2px;"></uni-icons>
					<text>{{curSkuData?.id}}</text>
					<text style="padding: 4px;">-</text>
					<text selectable style="font-weight: bold;">{{curSkuData?.name}}</text>
				</view>
				<view class="">
					<view class="gl-button gl-button-base" hover-class="button-base-hover" :hover-stay-time="100"
						@click="refresh">
						<uni-icons type="reload" size="18" color="#fff"></uni-icons>
						<text style="font-size: small;">刷新</text>
					</view>
				</view>
			</view>
		</template>
		<scroll-view class="gl-body-row" scroll-y="true" :style="{height: ish+'px'}">
			<view v-if="curSkuData" style="display: flex;">
				<view class="ui-all"
					style="display: flex;flex-direction: column;gap: 10px;padding: 0 10px;position: relative;">
					<image :src="sConf.cos + (curSkuData?.icon || '/media/default/cover.png')" mode=""
						@click="changeCover" style="width: 128px;height: 128px;border-radius: 5px;"></image>
				</view>
				<view class="ui-all" style="display: flex;flex-direction: column;gap: 10px;">
					<view class="" style="display: flex;gap: 20px;width: 100%;">
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">产品名称:</text>
							<uni-easyinput v-model="curSkuData.name" trim="all"
								@confirm="spuNameChange"></uni-easyinput>
						</view>
					</view>
					<view class="" style="display: flex;gap: 20px;">
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">条码:</text>
							<uni-easyinput v-model="curSkuData.idcode" trim="all" type="number"
								:disabled="Boolean(curSkuData.sku)" @confirm="spuIdcodeChange"></uni-easyinput>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">货号:</text>
							<uni-easyinput v-model="curSkuData.sdcode" trim="all" :disabled="Boolean(curSkuData.sku)"
								@confirm="spuSdcodeChange"></uni-easyinput>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">SKU:</text>
							<uni-easyinput v-model="curSkuData.sku" trim="all" disabled></uni-easyinput>
						</view>
					</view>
					<view v-if="false" class="" style="display: flex;gap: 20px;">
						<view class="ui-list" style="display: flex;align-items: center;gap: 5px;width: 100%;">
							<text style="font-weight: bold;">状态:</text>
							<switch :checked="Boolean(curSkuData.status)" style="transform:scale(0.7)"
								:disabled="Boolean(curSkuData.sku)" @change="EventStatusChange" />
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 5px;width: 100%;">
							<text style="font-weight: bold;">上架:</text>
							<switch :checked="Boolean(curSkuData.is_line)" style="transform:scale(0.7)"
								@change="EventLineChange" />
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 5px;width: 100%;">
							<text style="font-weight: bold;">卡券:</text>
							<switch :checked="Boolean(curSkuData.card)" style="transform:scale(0.7)"
								@change="EventCardChange" />
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 5px;width: 100%;">
							<text style="font-weight: bold;">折扣:</text>
							<switch :checked="Boolean(curSkuData.discount)" style="transform:scale(0.7)"
								@change="EventDistChange" />
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 5px;width: 100%;">
							<text style="font-weight: bold;">立返:</text>
							<switch :checked="Boolean(curSkuData.is_back)" style="transform:scale(0.7)"
								@change="EventBackChange" />
						</view>
					</view>


					<view class="" style="display: flex;gap: 20px;">
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">指导价(分):</text>
							<uni-easyinput v-model="curSkuData.money " trim="all" type="number"
								@change="EventMoneyChange"></uni-easyinput>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">结算价(分):</text>
							<uni-easyinput v-model="curSkuData.price " trim="all" type="number"
								@change="EventPriceChange"></uni-easyinput>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">悦玺币(分):</text>
							<uni-easyinput v-model="curSkuData.setprice " trim="all" type="number"
								@change="EventTokenChange"></uni-easyinput>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">积分价:</text>
							<uni-easyinput v-model="curSkuData.point " trim="all" type="number"
								@change="EventPointChange"></uni-easyinput>
						</view>

					</view>

					<view class="" style="display: flex;gap: 20px;">
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;">
							<uni-data-select v-model="curSkuData.sku_mode" :localdata="modeArray" emptyTips="没有"
								label="产品类型" placeholder="指定产品类型" style="width: 280px;"
								@change="EventSkuModeChange"></uni-data-select>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;">
							<uni-data-select v-model="curSkuData.pay_mode" :localdata="paysArray" emptyTips="没有"
								label="结算模型" placeholder="指定结算模型" style="width: 280px;"
								@change="EventPaysModeChange"></uni-data-select>
							<view class="gl-link gl-link-base" @tap="showPopLevel(curSkuData.pay_mode)">
								<text>查看</text>
							</view>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">当前库存:</text>
							<uni-easyinput v-model="curSkuData.fund" trim="all" type="number"
								:disabled="Boolean(curSkuData.sku)" @change="EventFundChange"></uni-easyinput>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">显示销量:</text>
							<uni-easyinput v-model="curSkuData.hot" trim="all" type="number"
								@change="EventHotChange"></uni-easyinput>
						</view>
					</view>

					<view class="" style="display: flex;gap: 20px;">
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">创建时间:</text>
							<text>{{curSkuData?.created}}</text>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">最近编辑:</text>
							<text>{{curSkuData?.lasttime}}</text>
						</view>
						<view class="ui-list" style="display: flex;align-items: center;gap: 10px;width: 100%;">
							<text style="font-weight: bold;">累计销量:</text>
							<text style="font-weight: bold;">筹建中...</text>
						</view>
					</view>
				</view>
			</view>
			<uni-section v-if="curSkuData" title="赠品列表" sub-title="赠品不能添加与主体相同的SKU">
				<view class="table-container">
					<uni-table class="uni-table" emptyText="暂无更多数据">
						<uni-tr class="table-head">
							<uni-th align="center">序号</uni-th>
							<uni-th>sku</uni-th>
							<uni-th>数量</uni-th>
							<uni-th>
								<view style="display: flex;gap: 10px;">
									<view class="gl-link gl-link-success" @click="searchGiftSku">
										<text>新增</text>
									</view>
									<view class="gl-link gl-link-base" @click="saveGiftSku">
										<text>保存</text>
									</view>
								</view>
							</uni-th>
						</uni-tr>
						<uni-tr v-for="(item,index) in giftArray" :key="index">
							<uni-td align="center">{{(index + 1)+''}}</uni-td>
							<uni-td>
								<blockSkuVue :sku="item.sku" :key="(item.sku+index)+''" />
							</uni-td>
							<uni-td><uni-number-box v-model="item.num" :min="1" :max="999999" /></uni-td>
							<uni-td>
								<view class="gl-link gl-link-error" @click="removeSku(index)">
									<text>移除</text>
								</view>
							</uni-td>
						</uni-tr>
					</uni-table>
				</view>
			</uni-section>
			<uni-section v-if="curSkuData" title="限购策略" sub-title="没有条目则无限购">
				<view class="table-container">
					<uni-table class="uni-table" emptyText="暂无更多数据">
						<uni-tr class="table-head">
							<uni-th align="center">序号</uni-th>
							<uni-th>权益等级</uni-th>
							<uni-th>最大限购</uni-th>
							<uni-th>最小数量</uni-th>
							<uni-th>步进值</uni-th>
							<uni-th>
								<view style="display: flex;gap: 10px;">
									<view class="gl-link gl-link-success" @click="searchLevel">
										<text>新增</text>
									</view>
									<view class="gl-link gl-link-base" @click="saveLevel">
										<text>保存</text>
									</view>
								</view>
							</uni-th>
						</uni-tr>
						<uni-tr v-for="(item,index) in limtArray" :key="index">
							<uni-td align="center">{{(index + 1)+''}}</uni-td>
							<uni-td>
								<blockLevelVue :sku="item.level" :key="(item.level+index)+''" />
							</uni-td>
							<uni-td>
								<uni-number-box v-model="item.maxCount" :min="0" :max="999999" />
							</uni-td>
							<uni-td>
								<uni-number-box v-model="item.minCount" :min="1" :max="999999" />
							</uni-td>
							<uni-td>
								<uni-number-box v-model="item.step" :min="1" :max="999999" />
							</uni-td>
							<uni-td>
								<view class="gl-link gl-link-error" @click="removeLevel(index)">
									<text>移除</text>
								</view>
							</uni-td>
						</uni-tr>
					</uni-table>
				</view>
			</uni-section>

			<view class="" style="height: 30vh;">
				<!-- 产品封面上传 -->
				<cos-multiple-post ref="cosCover" :host="sConf.host" :token="sConf.auth.token" path="product" onHide
					once @upFinish="EventFinish"></cos-multiple-post>
				<popSkuSelectVue ref="popSkuSelect" desc="选择1个SKU" @change="hasOneSku"></popSkuSelectVue>
				<popLevelSelectVue ref="popLevelSelect" desc="选择权益等级" multi @change="hasOneLevel"></popLevelSelectVue>
				<popLevelCardVue ref="popLevelCard"></popLevelCardVue>
			</view>

		</scroll-view>
	</uni-card>
</template>

<script>
	import psMethod from '@/common/psMethod';
	import popSkuSelectVue from './pop-sku-select.vue';
	import popLevelSelectVue from '../sub-staff-list/pop-level-select.vue';
	import blockSkuVue from './block-sku.vue';
	import blockLevelVue from './block-level.vue';
	import popLevelCardVue from '@/components/level-list/pop-level-card.vue'
	export default {
		data() {
			return {
				ish: 0,
				sConf: getApp().globalData,
				curSkuData: null,
				modeArray: [],
				paysArray: [],
				giftArray: [],
				limtArray: []
			}
		},
		mounted() {
			console.log('mounted');
			this.loadSkuModeList()
			this.loadPaysModeList()
			this.designLayout()
		},
		updated() {
			console.log('...updated...');
			if (!this.curSkuData || this.curSkuData.id !== this.data?.id) {
				this.refresh()
			}
		},
		components: {
			popSkuSelectVue,
			popLevelSelectVue,
			blockSkuVue,
			blockLevelVue,
			popLevelCardVue
		},
		props: {
			data: {
				type: Object,
				default: Array
			},
			isback: {
				type: Boolean,
				default: false
			}
		},
		methods: {
			filterPayMode(e) {
				return this.paysArray.find(item => item.id === e)
			},
			/**
			 * 查看权益
			 */
			showPopLevel(e) {
				let data = this.filterPayMode(e)
				this.$refs.popLevelCard.open(data)
			},
			/**
			 * 编辑限购
			 */
			hasOneLevel(e) {
				console.log('hasOneLevel', e);
				e.forEach(level => {
					this.limtArray.push({
						level: parseInt(level),
						maxCount: 0,
						minCount: 1,
						step: 1
					})
				})
			},
			searchLevel() {
				this.$refs.popLevelSelect.open()
			},
			removeLevel(e) {
				this.limtArray.splice(e, 1)
			},
			saveLevel() {
				this.EventDataChange({
					need_level: JSON.stringify(this.limtArray)
				})
			},
			/**
			 * 编辑赠品
			 */
			hasOneSku(e) {
				console.log('hasOneSku', e);
				let sku = parseInt(e)
				if (sku === this.data.id) {
					uni.showToast({
						title: '不能添加自己'
					})
					return
				}
				this.giftArray.push({
					sku: sku,
					num: 1
				})
			},
			removeSku(e) {
				console.log('removeSku', e);
				this.giftArray.splice(e, 1)
			},
			searchGiftSku() {
				this.$refs.popSkuSelect.open()
			},
			saveGiftSku() {
				this.EventDataChange({
					sku_bind: JSON.stringify(this.giftArray)
				})
			},
			/**
			 * 编辑模型
			 */
			EventSkuModeChange(e) {
				console.log('EventSkuModeChange', e);
				if (!e) {
					return
				}
				this.EventDataChange({
					sku_mode: e
				}, false)
			},
			EventPaysModeChange(e) {
				console.log('EventPaysModeChange', e);
				if (!e) {
					return
				}
				this.EventDataChange({
					pay_mode: e
				}, false)
			},
			/**
			 * 编辑价格
			 */
			EventMoneyChange(e) {
				console.log('EventMoneyChange', e);
				if (!e || e < 0) {
					return
				}
				let data = {
					money: e
				}
				let that = this
				uni.showModal({
					title: '提交修改',
					content: '是否要提交本次修改',
					success(r) {
						if (r.confirm) {
							that.EventDataChange(data)
						}
					}
				})
			},
			EventPriceChange(e) {
				if (!e || e < 0) {
					return
				}
				let data = {
					price: e
				}
				let that = this
				uni.showModal({
					title: '提交修改',
					content: '是否要提交本次修改',
					success(r) {
						if (r.confirm) {
							that.EventDataChange(data)
						}
					}
				})
			},
			EventPointChange(e) {
				if (!e || e < 0) {
					return
				}
				let data = {
					point: e
				}
				let that = this
				uni.showModal({
					title: '提交修改',
					content: '是否要提交本次修改',
					success(r) {
						if (r.confirm) {
							that.EventDataChange(data)
						}
					}
				})
			},
			EventTokenChange(e) {
				if (!e || e < 0) {
					return
				}
				let data = {
					setprice: e
				}
				let that = this
				uni.showModal({
					title: '提交修改',
					content: '是否要提交本次修改',
					success(r) {
						if (r.confirm) {
							that.EventDataChange(data)
						}
					}
				})
			},
			EventHotChange(e) {
				if (!e || e < 0) {
					return
				}
				let data = {
					hot: e
				}
				let that = this
				uni.showModal({
					title: '提交修改',
					content: '是否要提交本次修改',
					success(r) {
						if (r.confirm) {
							that.EventDataChange(data)
						}
					}
				})
			},
			EventFundChange(e) {
				if (!e || e < 0) {
					return
				}
				let data = {
					fund: e
				}
				let that = this
				uni.showModal({
					title: '提交修改',
					content: '是否要提交本次修改',
					success(r) {
						if (r.confirm) {
							that.EventDataChange(data)
						}
					}
				})


			},
			/**
			 * 编辑状态
			 */
			EventStatusChange(e) {
				let data = {
					status: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, false)
			},
			EventLineChange(e) {
				let data = {
					is_line: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, false)
			},
			EventCardChange(e) {
				let data = {
					card: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, false)
			},
			EventDistChange(e) {
				let data = {
					discount: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, false)
			},
			EventBackChange(e) {
				let data = {
					is_back: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, false)
			},

			/**
			 * 编辑条码,编辑货号
			 */
			spuIdcodeChange(e) {
				let code = e.trim()
				if (this.data.idcode === code) {
					return
				}
				this.EventDataChange({
					idcode: code
				})
			},
			spuSdcodeChange(e) {
				let code = e.trim()
				if (this.data.sdcode === code) {
					return
				}
				this.EventDataChange({
					sdcode: code
				})
			},
			/**
			 * 编辑名称
			 */
			spuNameChange(e) {
				console.log('spuNameChange', e);
				let name = e.trim()
				if (!name) {
					return
				}
				if (name === this.data.name) {
					return
				}
				let data = {
					name: name
				}
				this.EventDataChange(data)
			},
			/**
			 * 上传封面
			 */
			changeCover() {
				this.$refs.cosCover.open()
			},
			EventFinish(e) {
				console.log('EventFinish', e);
				this.curSkuData.icon = e[0];
				let data = {
					icon: e[0]
				}
				this.EventDataChange(data)
			},
			/**
			 * 编辑字段
			 */
			EventDataChange(data, msg = true) {
				let that = this
				let index = this.curSkuData.id
				let token = this.sConf.auth.token || '';
				psMethod.syncAuthenticatorRequest(`/admin/cargoSku/${index}/`, 'PATCH', token, data).then(res => {
					this.curSkuData = res.resmsg
					if (msg) {
						uni.showToast({
							title: '提交请求完成',
							success() {
								that.refresh()
							}
						})
					}
				}).catch(err => {
					if (!msg) {
						uni.showToast({
							title: '提交请求失败',
							success() {
								that.refresh()
							}
						})
					}
				})
			},
			refresh() {
				console.log('refresh');
				let sku = this.data?.id || null
				if (!sku) {
					return
				}
				let token = this.sConf.auth.token || '';
				psMethod.syncAuthenticatorRequest(`/admin/cargoSku/${sku}/`, 'GET', token).then(res => {
					console.log('加载SKU', res);
					this.curSkuData = res.resmsg
					if (res.resmsg.sku_bind) {
						this.giftArray = JSON.parse(res.resmsg.sku_bind)
					} else {
						this.giftArray = []
					}
					if (res.resmsg.need_level) {
						this.limtArray = JSON.parse(res.resmsg.need_level)
					} else {
						this.limtArray = []
					}
				})
			},
			swiperBack() {
				this.$emit('toback')
			},
			loadSkuModeList() {
				psMethod.syncAnonymousRequest('/api/skuMode/', 'POST', {}).then(res => {
					console.log('加载skuMode', res);
					this.modeArray = res.resmsg
				})
			},
			loadPaysModeList() {
				let token = this.sConf.auth.token || '';
				psMethod.syncAuthenticatorRequest('/admin/modeName/', 'GET', token, {
					status: 1
				}).then(res => {
					console.log('加载结算模型', res);
					this.paysArray = res.resmsg
				})
			},
			designLayout() {
				let window = uni.getWindowInfo();
				let wh = window.windowHeight;
				let query = uni.createSelectorQuery().in(this);
				query.select('.gl-body-row').boundingClientRect();
				query.exec((res) => {
					this.ish = wh - Math.ceil(res[0].top) - 40;
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 表格垂直滚动 */
	.table-container {
		/* height: 400px; */
		overflow-y: auto;

		::v-deep .uni-table .table-head th {
			font-weight: bold;
			z-index: 2;
			background-color: #fff;
			position: -webkit-sticky;
			position: sticky;
			top: 0;
		}

		::v-deep .uni-table-scroll {
			overflow: visible;
		}
	}
</style>